package com.lysj.admin.gateway.filter;

import com.lysj.admin.common.result.domain.AuthenticationResult;
import com.lysj.admin.gateway.constants.GatewayConstants;
import com.lysj.admin.gateway.feign.MerchantFeign;
import com.lysj.admin.utils.json.JacksonUtil;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author Created by wtl on 2019-03-14 10:25
 * @description
 */
public class MerchantFilter extends MyAbstractPreZuulFilter {
    @Resource
    private MerchantFeign MerchantFeign;
    @Resource
    private MerchantFeign merchantFeign;
    @Value("${secret.header}")
    private String header;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 5;
    }

    @Override
    public boolean shouldFilter() {
        if (!super.shouldFilter()) {
            return false;
        }
        if ("merchant".equals(getIssName())) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        AuthenticationResult authenticationResult = merchantFeign.authentication(getToken(), request.getRequestURI());
        if (!authenticationResult.getStatus().equals(AuthenticationResult.ResultStatus.SUCCESS)) {
            request.setAttribute(GatewayConstants.IS_SUCCESS_NAME, false);
            ctx.setSendZuulResponse(false);
            ctx.setResponseBody(JacksonUtil.toJson(authenticationResult));
            ctx.getResponse().setContentType("application/json; charset=utf-8");
            return null;
        }
        ctx.getResponse().setHeader(header, authenticationResult.getMsg());
        return null;
    }
}
